package com.zxy.hotel.controller;


import com.zxy.hotel.entity.RS;
import com.zxy.hotel.service.AdminService;
import com.zxy.hotel.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jiusi
 * @since 2021-12-12
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AdminService adminService;

    @PostMapping("/login")
    public RS login(String username, String password) {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (userDetails == null || !passwordEncoder.matches(password, userDetails.getPassword())) {
            return RS.fail().message("用户名或密码错误");
        }
        //将当前用户对象存入SpringSecurity全局上下文，方便其他方法使用
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,
                null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String token = JwtUtil.createToken(userDetails.getUsername());
        HashMap<String, String> map = new HashMap<>();
        map.put("token", token);
        map.put("tokenHead", "Bearer");
        return RS.ok().data(map);
    }

    @PostMapping
    @PreAuthorize("hasRole('root')")
    public RS addAdmin(String adminName, String adminAccount, String adminPassword, String adminRole) {
        if (!StringUtils.hasText(adminAccount) || !StringUtils.hasText(adminName) || !StringUtils.hasText(adminPassword) || !StringUtils.hasText(adminRole)) {
            return RS.fail().message("请输入完整");
        }
        Integer i = adminService.addAmin(adminName, adminAccount, adminPassword, adminRole);

        return RS.ok().data(i);
    }
}
